package com.sgcc.pda.mdrh.task.monitor

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Vibrator
import android.util.Log
import android.view.View
import cn.bingoogolapple.qrcode.core.BarcodeType
import com.jeremyliao.liveeventbus.LiveEventBus
import com.sgcc.pda.mdrh.task.base.BaseActivity
import com.sgcc.pda.mdrh.task.common_ui.helper.ActivityStack
import com.sgcc.pda.mdrh.task.util.setDelegate
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_scan.*
import java.util.concurrent.TimeUnit

class ScanActivity : BaseActivity() {

    private var isFlashlighting = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan)
        setTransparentAndToolbar(isDarkFont = false)
        initTitle()
    }

    override fun initTitle(title: String, name: String, divider: Boolean) {
        scan_zxing.setDelegate {
            onScanQRCodeSuccess {
                Log.i("zxing", it ?: "")
                vibrate()

                when (it) {
                    null -> resetZxing("扫描失败，请重试！")
                    else -> {
                        if (it.length == 12) {
                            val items = ArrayList<String>()
                            for (i in it.indices step 2) {
                                items.add(it.substring(i, i + 2))
                            }

                            LiveEventBus.get("blue_scan").post(items.joinToString(":"))
                            ActivityStack.screenManager.popActivities(this@ScanActivity::class.java)
                        } else {
                            resetZxing("无效二维码，请重新扫描！")
                        }
                    }
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        scan_zxing.startCamera() //打开后置摄像头开始预览，但是并未开始识别
        scan_zxing.setType(BarcodeType.ALL, null)
        scan_zxing.startSpotAndShowRect() //显示扫描框，并开始识别
    }

    override fun onStop() {
        super.onStop()
        scan_zxing.stopCamera() //关闭摄像头预览，并且隐藏扫描框
    }

    private fun vibrate() {
        val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        @Suppress("DEPRECATION")
        vibrator.vibrate(200)
    }

    @SuppressLint("CheckResult", "AutoDispose")
    private fun resetZxing(hint: String = "") {
        if (hint.isNotEmpty()) {
            showToast(hint)
        }

        Completable.timer(2, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { scan_zxing.startSpotAndShowRect() }
    }

    override fun doClick(v: View) {
        super.doClick(v)
        when (v.id) {
            R.id.scan_light_ll -> {
                isFlashlighting = if (isFlashlighting) {
                    scan_zxing.closeFlashlight()
                    scan_light.setImageResource(R.mipmap.icon_light01)
                    scan_light_hint.text = "轻触照亮"
                    false
                } else {
                    scan_zxing.openFlashlight()
                    scan_light.setImageResource(R.mipmap.icon_light02)
                    scan_light_hint.text = "轻触关闭"
                    true
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        scan_zxing.onDestroy() //销毁二维码扫描控件
    }

}
